package com.jsoup.config;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.util.Assert;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

@Component
public class StringToTimestampConfig implements Converter<String, Timestamp> {
    //接收的时间格式
    private final static String[] dateFormats = {
            "EEE, d MMM yyyy HH:mm:ss z",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "yyyy-MM-dd HH:mm:ss.SSSZ",
            "yyyy-MM-dd HH:mm:ssZ",
            "yyyy-MM-dd HH:mm:ss.SSS",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd"};

    @Override
    public Timestamp convert(String source) {
        Assert.hasText(source, "空的时间字符串");
        Date date = null;
        try {
            date = DateUtils.parseDate(source.trim(), dateFormats);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) {
            String errMsg = String.format("时间格式化失败 [%s] to [%s] '%s'", String.class.toString(), Date.class.toString(), source);
            throw new IllegalArgumentException(errMsg);
        }
        return new Timestamp(date.getTime());
    }
}
